package com.baosight.risk.common.quartz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.zbaa.IZbaaTargetService;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.IDGenerator;
import com.baosight.risk.common.utils.ReadProperties;
import com.baosight.risk.mapper.system.SysInterfaceDataLogMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetValueMapper;
import com.baosight.risk.service.riwa.entity.RiwaEhrContractValue;
import com.baosight.risk.service.riwa.entity.RiwaTargetActualsValue;
import com.baosight.risk.service.system.entity.SysInterfaceDataLogEntity;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.zbaa.entity.ZbaaTarget;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetValue;
import com.baosight.risk.service.zbaa.vo.CarboardRequest;
import com.baosight.risk.service.zbaa.vo.CarboardResponse;

import com.baosight.risk.webservice.WsCall;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: Liuhaonan
 * @Date: 2020/5/22
 * @description: 汽车板相关销量接口
 */
@Slf4j
@Component("riwaTargetActualsTask")
public class RiwaTargetActualsTask {
    @Autowired
    private FltdProcessService fltdProcessService;
    @Autowired
    ZbaaTargetValueMapper zbaaTargetValueMapper;
    @Autowired
    IZbaaTargetService targetService;
    @Autowired
    SysInterfaceDataLogMapper logMapper;


    // 测试环境
    private final String URL = ReadProperties.getValueString("riwaTargetActualsTask.url");
    //private final String URL = "http://10.60.17.16:8084/baosteel_csm/services/yhybKpiServise";



    //获取汽车板相关销量接口数据
    public void testParams(String params, String jobId) throws Exception {
        getDataByMonth(params, jobId);
    }

    //每个月一跑
    private void getDataByMonth(String params, String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;

        CarboardRequest param = new CarboardRequest();
        param.setDomExp("外销");
        param.setNodeId("10");
        //算出上个月的年份
        String lastYear = getLastMonth().substring(0,4);
        param.setYear(lastYear);
        try {
            String s = sendRequest(param);
            SysInterfaceDataLogEntity entity = new SysInterfaceDataLogEntity();

            //别忘了通过这个去重   这里是最新的上个月份
            entity.setLastMonth(getLastMonth());
            List<SysInterfaceDataLogEntity> select = logMapper.select(entity);

            if (select.size() == 0){
                entity.setId(IDGenerator.getIdStr());
                entity.setData(s);
                entity.setInterfaceName("内部指标接口获取");
                logMapper.insert(entity);
            }
            ZbaaTargetValue query = new ZbaaTargetValue();
            query.setTargetNo("ZBN0053");

            ZbaaTargetValue zbaaTargetValue = handleData(s);
            if (zbaaTargetValue!=null){
                zbaaTargetValueMapper.insert(zbaaTargetValue);
                logs.add(fltdProcessService.getLog("获取汽车板销量数据定时任务执行成功", 0, "", jobId));
            }
        }catch (Exception e){
            error = e;
            log.error("获取汽车板销量数据异常！");
            logs.add(fltdProcessService.getLog("获取汽车板销量数据定时任务执行失败", 1, e.getMessage(), jobId));
        }

        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }






    }

    /**
     * 处理json字符串
     * @param s
     * @return
     */
    private ZbaaTargetValue handleData(String s) {
        ZbaaTargetValue zbaaTargetValue = new ZbaaTargetValue();
        ZbaaTargetValue zbaaTargetValueTask = zbaaTargetValueMapper.checkMaxDateTask();
        //计算错误 这里是上个月所属的季度
       String lastQuarter = dealQuarter(getLastMonth());
        try {
            String substring = s.substring(1, s.length() - 1);
            JSONObject jsonObject = JSONObject.parseObject(substring);
            //HashMap parseMap = JSON.parseObject(json, HashMap.class);
            String msg = jsonObject.getString("status");
            if (("200").equals(msg)){
                JSONArray data = jsonObject.getJSONArray("actuals");
                List<RiwaTargetActualsValue> list = JSONObject.parseArray(data.toJSONString(), RiwaTargetActualsValue.class);
                //上个季度

                Integer targetValue = 0;
                //表里数据为空直接处理添加
                if (zbaaTargetValueTask == null){
                    int t = 0;
                    for (RiwaTargetActualsValue value:list){
                        String valueQuarter = dealQuarter(value.getYear());

                        if (valueQuarter.equals(lastQuarter)){
                            int i = Integer.parseInt(value.getActual());
                            targetValue += i;
                            t++;
                        }
                    }
                    if (t > 0){
                        ZbaaTargetValue value = copyValue(zbaaTargetValue, "a9fbd87c-26ee-40c2-b84d-160d31adb102",lastQuarter.substring(0,4),targetValue,lastQuarter);
                        return value;
                    }
                    return null;
                }
                //如果表里不为空则判断表里的最后一条数据是否是上个季度的
                if (!lastQuarter.equals(zbaaTargetValueTask.getPeriodNo())){
                    int t = 0;
                    for (RiwaTargetActualsValue a:list){
                        if (dealQuarter(a.getYear()).equals(lastQuarter)){
                            t++;
                            int i = Integer.parseInt(a.getActual());
                            targetValue+=i;
                        }

                    }
                    if (t > 0){
                        ZbaaTargetValue value = copyValue(zbaaTargetValue, "a9fbd87c-26ee-40c2-b84d-160d31adb102",lastQuarter.substring(0,4),targetValue,lastQuarter);
                        return value;
                    }

                }


            }

        }catch (Exception e){
            log.error("获取汽车板销量数据异常："+e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    public ZbaaTargetValue copyValue(ZbaaTargetValue zbaaTargetValue,String id,String year,int targetValue,String lastQuarter){
        ZbaaTarget target = targetService.get(id);
        BeanUtils.copyBeanProp(zbaaTargetValue,target);
        BeanUtils.initBean(zbaaTargetValue);
        BeanUtils.initExt(zbaaTargetValue);
        zbaaTargetValue.setAcctYear(year);
        double dValue = targetValue;
        dValue = dValue/10000;
        DecimalFormat    df   = new DecimalFormat("######0.00");
        String format = df.format(dValue);

        zbaaTargetValue.setTargetValue(format);
        zbaaTargetValue.setPeriodNo(lastQuarter);
        zbaaTargetValue.setAcctPeriod(lastQuarter.substring(5,6));
        return zbaaTargetValue;
    }


    /**
     * @description 调用方法
     * @author lishaoqing
     * @date 2020/5/18
     */
    public String sendRequest(CarboardRequest param) throws Exception {
        String namespace = "http://model.webservices.of.bsi.baosteel.baosight.com";
        String complexType = "YhybKpiDataCmd";

        WsCall call = new WsCall(URL, "queryYhybKpiData");
        call.init();
        String result = (String) call.invokeByNamespace(namespace, complexType, new CarboardRequest(), new CarboardResponse(), new CarboardRequest[]{param});
        System.out.println("调用结束！返回：" + result);
        return result;
    }

    /**
     * 获取上个月日期
     * @return
     */
    public String getLastMonth(){
        Calendar cal = Calendar.getInstance();

        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -3);
        int year3 = cal.get(Calendar.YEAR);
        int month3 = cal.get(Calendar.MONTH)+1;
        int day3 = cal.get(Calendar.DAY_OF_MONTH);
        System.out.println(year3 + " 年 " + month3 + " 月 " + day3 +  " 日");
        Date date3 = cal.getTime();
        SimpleDateFormat format3= new SimpleDateFormat("yyyyMM");
        String dateStringYYYYMMDD3 = format3.format(date3);
        return dateStringYYYYMMDD3;

    }

    /**
     * 判断是否是上个季度
     * @param periodNo
     * @return
     */
    public Boolean checkQ(String periodNo) {
        //算出当前日期的上个季度
        Date nowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        //当前日期
        String nowFormat = formatter.format(nowDate);
        nowFormat = nowFormat.substring(0,4) + nowFormat.substring(5,7);

        String nowYear = nowFormat.substring(0, 4);
        String nowMonth = nowFormat.substring(4, 6);
        String lastQuarter = "";
        switch (nowMonth) {
            case "01":
            case "02":
            case "03":
                lastQuarter = "Q4";
                nowYear = (Integer.parseInt(nowYear) - 1) + "";
                break;
            case "04":
            case "05":
            case "06":
                lastQuarter = "Q1";
                break;
            case "07":
            case "08":
            case "09":
                lastQuarter = "Q2";
                break;
            case "10":
            case "11":
            case "12":
                lastQuarter = "Q3";
                break;
        }
//        String taskYear = periodNo.substring(0, 4);
//        String taskQuarter = periodNo.substring(4, 6);

        return periodNo.equals(nowYear+lastQuarter);
    }

    /**
     * 判断是否日期属于上个季度
     * @param date
     * @return
     */
    public Boolean checkQuarter(String date){
        Date nowDate = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        //当前日期
        String nowFormat = formatter.format(nowDate);
        nowFormat = nowFormat.substring(0,4) + nowFormat.substring(5,7);
        int nowYear = Integer.parseInt(nowFormat.substring(0, 4));
        //进来的数据年份
        int taskYear = Integer.parseInt(date.substring(0, 4));
        int lastYear = nowYear - 1;

        if (taskYear == nowYear || taskYear == lastYear){
            //取当前月份和数据月份
            String substring = date.substring(5);
            int nMonth = 0;
            int tMonth = 0;
            try {
                nMonth = Integer.parseInt(nowFormat.substring(5));
                tMonth = Integer.parseInt(date.substring(5));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            //判断当前日期
            //第二季度
            if (nMonth >= 4 && nMonth <= 6){
                //先判断是否和当年为同一年,在判断是否为当前时间的上个季度
                if (taskYear != nowYear){
                    return false;
                }else {
                    if (tMonth >= 1 && tMonth <= 3){
                        return true;
                    }else return false;
                }
            }else if (nMonth > 6 && nMonth < 10){//第三季度
                if (taskYear != nowYear){
                    return false;
                }else {
                    if (tMonth >= 4 && tMonth <= 6){
                        return true;
                    }else return false;
                }
            }else if (nMonth > 9 && nMonth < 13){//第四季度
                if (taskYear != nowYear){
                    return false;
                }else {
                    if (tMonth >= 7 && tMonth <= 9){
                        return true;
                    }else return false;
                }
            }else {//第一季度
                if (taskYear != nowYear - 1 ){
                    return false;
                }else {
                    if (tMonth >= 10 && tMonth <= 12){
                        return true;
                    }else return false;
                }
            }
        }
        return false;
    }

    /**
     * @param periodNo 周期
     * @return
     * @description 描述
     */
    public String dealQuarter(String periodNo) {
        String year = periodNo.substring(0, 4);
        String month = periodNo.substring(4, 6);
        String result = "";
        switch (month) {
            case "01":
            case "02":
            case "03":
                result = "Q1";
                break;
            case "04":
            case "05":
            case "06":
                result = "Q2";
                break;
            case "07":
            case "08":
            case "09":
                result = "Q3";
                break;
            case "10":
            case "11":
            case "12":
                result = "Q4";
                break;
        }
        return year + result;
    }
}
